package _05_stack.my_implements;

import _05_stack.AbstractStack;

import java.util.Iterator;

/**
 * @author: mornd
 * @dateTime: 2023/6/6 - 16:51
 * 基于数组实现
 */
public class ArrayStack<E> extends AbstractStack<E> {
    E[] elementData;
    int capacity;

    int top;

    @SuppressWarnings("all")
    public ArrayStack(int capacity) {
        if(capacity < 0) {
            throw new IllegalArgumentException();
        }
        this.capacity = capacity;
        elementData = (E[]) new Object[this.capacity];
    }

    /*
        1   2  3  4  5
     */
    @Override
    public boolean push(E e) {
        if(isFull()) {
            return false;
        }
        elementData[top++] = e;
        return true;
    }

    @Override
    public E pop() {
        if(isEmpty()) {
            return null;
        }
        E e = elementData[top - 1];
        elementData[top - 1] = null;
        --top;
        return e;
    }

    @Override
    public E peek() {
        if(isEmpty()) {
            return null;
        }
        return elementData[top - 1];
    }

    @Override
    public boolean isEmpty() {
        return top == 0;
    }

    @Override
    public boolean isFull() {
        return top == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int count = top;
            @Override
            public boolean hasNext() {
                return count != 0;
            }

            @Override
            public E next() {
                return elementData[--count];
            }
        };
    }

    @Override
    public int size() {
        return top;
    }
}
